//
//  CalDataModelController.m
//  JiaoWuGuanLi
//
//  Created by Zinzie on 14-4-16.
//  Copyright (c) 2014年 Zinzie. All rights reserved.
//
#import "CalDataModel.h"
#import "CalDataModelController.h"
#import "TFHpple.h"
#import "MainInterfaceAppDelegate.h"
#import "Student.h"
#import "Classes.h"
#import "CoreData+MagicalRecord.h"


@implementation CalDataModelController

-(void)dealCalDataModelWithWeek:(CalDataModel *)calmodel
                   withDayArray:(NSMutableArray *)dayArray
{
    if (calmodel.specialMark==0) {
        [dayArray addObject:calmodel];
    }else if (calmodel.specialMark==1&&self.week%2==0){
        [dayArray addObject:calmodel];
    }else if (calmodel.specialMark==2&&self.week%2==1){
        [dayArray addObject:calmodel];
    }
    
}

-(void)setLoadingList:(NSMutableArray *)loadingList{

    NSLog(@"loadingList333333333333333");
    _loadingList = [loadingList mutableCopy];
    [self spreadLoadingListToDayArray];
    //========================== start ===============
/*
    NSMutableIndexSet *set =[[NSMutableIndexSet alloc]init];
    
    for (CalDataModel *calmodel in _loadingList) {
        if (calmodel.specialMark==1&&self.week%2==0) {
            [set addIndex:[self.loadingList indexOfObject:calmodel]];
        }
        else if (calmodel.specialMark==2&&self.week%2==1) {
            [set addIndex:[self.loadingList indexOfObject:calmodel]];
        }
        else if (calmodel.xingQi != self.xingqi || calmodel.kaiShiZhou > self.week || calmodel.jieShuZhou < self.week ) {
            [set addIndex:[self.loadingList indexOfObject:calmodel]];
        }
    }
    [self.loadingList removeObjectsAtIndexes:set];
*/
    //==========================end===============
    
//    for (CalDataModel *calmodel in _loadingList) {
//        if ([calmodel.shiJian isEqualToString:@"1"]) {
//            CalDataModel *calmodel2 = [self.loadingList objectAtIndex:([self.loadingList indexOfObject:calmodel]                +1)];
//            if ([calmodel.mingCheng isEqualToString:calmodel2.mingCheng]) {
//
//            }
//        }
//    }
}

-(void)spreadLoadingListToDayArray{
    NSLog(@"loding list have %d class",self.loadingList.count);
    for (CalDataModel *calmodel in self.loadingList) {
        if (calmodel.xingQi==1&&calmodel.kaiShiZhou <= self.week&&calmodel.jieShuZhou >= self.week ) {
            [self dealCalDataModelWithWeek:calmodel withDayArray:self.mon];
        }
        else if (calmodel.xingQi==2&&calmodel.kaiShiZhou <= self.week&&calmodel.jieShuZhou >= self.week) [self dealCalDataModelWithWeek:calmodel withDayArray:self.tue];
        else if (calmodel.xingQi==3&&calmodel.kaiShiZhou <= self.week&&calmodel.jieShuZhou >= self.week) [self dealCalDataModelWithWeek:calmodel withDayArray:self.wed];
        else if (calmodel.xingQi==4&&calmodel.kaiShiZhou <= self.week&&calmodel.jieShuZhou >= self.week) [self dealCalDataModelWithWeek:calmodel withDayArray:self.thu];
        else if (calmodel.xingQi==5&&calmodel.kaiShiZhou <= self.week&&calmodel.jieShuZhou >= self.week) [self dealCalDataModelWithWeek:calmodel withDayArray:self.fri];
        else if (calmodel.xingQi==6&&calmodel.kaiShiZhou <= self.week&&calmodel.jieShuZhou >= self.week) [self dealCalDataModelWithWeek:calmodel withDayArray:self.sat];
        else if (calmodel.xingQi==7&&calmodel.kaiShiZhou <= self.week&&calmodel.jieShuZhou >= self.week) [self dealCalDataModelWithWeek:calmodel withDayArray:self.sun];
        
    }
    NSArray *dayArray = [[NSArray alloc]initWithObjects:self.mon,self.tue,self.wed,self.thu,self.fri,self.sat,self.sun, nil];
    NSMutableArray *sortedDayArray = [[NSMutableArray alloc]init];
    for (NSMutableArray *day in dayArray) {
        NSLog(@"other day");
        NSArray *sortedArray = [[NSArray alloc] init];
        sortedArray = [day sortedArrayUsingComparator:^NSComparisonResult(Classes *obj1, Classes *obj2) {
            NSString *time1 = obj1.shiJian;
            NSString *time2 = obj2.shiJian;
            NSLog(@"Time is %@ and %@",time1,time2);
            
            NSComparisonResult result = [time1 compare:time2];
            return result == NSOrderedDescending;
            
        }];
        [sortedDayArray addObject:sortedArray];
    }
    if (sortedDayArray.count!=0) {
        self.mon = [sortedDayArray[0] mutableCopy];
        self.tue = [sortedDayArray[1] mutableCopy];
        self.wed = [sortedDayArray[2] mutableCopy];
        self.thu = [sortedDayArray[3] mutableCopy];
        self.fri = [sortedDayArray[4] mutableCopy];
        self.sat = [sortedDayArray[5] mutableCopy];
        self.sun = [sortedDayArray[6] mutableCopy];
    }
    NSLog(@"lodinglist %d",self.loadingList.count);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ShuXinClassesOK" object:self];
}
-(id)init{
    if (self = [super init]) {
        self.weekList = [[NSMutableArray alloc]init];
        self.loadingList=[[NSMutableArray alloc]init];
        //        [self jiaZaiChengJi];
        self.mon =[[NSMutableArray alloc]init];
        self.tue =[[NSMutableArray alloc]init];
        self.thu =[[NSMutableArray alloc]init];
        self.wed =[[NSMutableArray alloc]init];
        self.fri =[[NSMutableArray alloc]init];
        self.sat =[[NSMutableArray alloc]init];
        self.sun =[[NSMutableArray alloc]init];
        [self presentClassesInCalDataModel];
        return self;
    }
    return nil;
}

-(void)acquireData{
    
    AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
    
    MainInterfaceAppDelegate *mainDele=[[UIApplication sharedApplication]delegate];
    NSString *uName=mainDele.userName;
    NSString *zhangHao=mainDele.XueHao;
    if(uName!=nil&&zhangHao!=nil){
    NSDictionary *parameters2 = @{@"xh":zhangHao,@"xm":uName,@"gnmkdm":@"N121603"};
    manager2.responseSerializer = [AFHTTPResponseSerializer serializer];
    [self.AFHROM GET:@"http://gdjwgl.bjut.edu.cn/xskbcx.aspx?" parameters:parameters2
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
              
              NSData *data=responseObject;
              NSString *transStr=[[NSString alloc]initWithData:data encoding:enc];
              
              NSLog(@"huoqushuju: %ld",(long)operation.response.statusCode);
              NSLog(@"课表数据：%@",transStr);
              NSString *utf8HtmlStr = [transStr stringByReplacingOccurrencesOfString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">" withString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"];
              NSData *htmlDataUTF8 = [utf8HtmlStr dataUsingEncoding:NSUTF8StringEncoding];
              TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:htmlDataUTF8];
              NSArray *elements  = [xpathParser searchWithXPathQuery:@"//table[@id='Table1']/tr/td/child::text()"];
              
              // Access the first cell
              NSUInteger count=[elements count];
              NSMutableArray *allContents=[NSMutableArray array];
              for (int i=0; i<count; i++) {
                  
                  TFHppleElement *element = [elements objectAtIndex:i];
                  
                  // Get the text within the cell tag
//                  NSString *content = [element text];
                  NSString *ta=[element tagName];
//                  NSDictionary *dic=[element attributes];
                  NSString *nodeContent=[element content];
                  NSLog(@"课程为%@%@",nodeContent,ta);
                  [allContents addObject:nodeContent];
              }
              
              [self sortData:allContents];
              
              [allContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                  NSLog(@"整理后的数据%@",obj);
              }];
              
              
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"Error: %@", [error debugDescription]);
          }];//获取登陆后的网页
    }
}
-(void)sortData:(NSMutableArray*)arrayData{
    
    __block NSMutableIndexSet* indexSet=[NSMutableIndexSet indexSet];
    [arrayData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *string=obj;
        if([string isEqualToString:@" "]||[string hasPrefix:@"星期"]||[string isEqualToString:@"上午"]||[string isEqualToString:@"下午"]||[string isEqualToString:@"早晨"]||[string isEqualToString:@"晚上"]){
            [indexSet addIndex:idx];
        }
        if([string hasPrefix:@"第"]&&[string hasSuffix:@"节"]){
            [indexSet addIndex:idx];
        }
        if([string isEqualToString:@"时间"]){
            [indexSet addIndex:idx];
        }
        if ([string hasPrefix:@"2014年"]) {
            [indexSet addIndex:idx];
            [indexSet addIndex:idx+1];
        }
        
    }];
    [arrayData removeObjectsAtIndexes:indexSet];
    long count=arrayData.count;
    if(count%4==0){////////////////////
    NSLog(@"一共有%lu节课程",count/4);
    NSMutableArray *cach=[NSMutableArray array];
    for(int i=0;i<arrayData.count/4;i++){
//        NSString *source = arrayData[i*4+1];
//        NSRange week = NSMakeRange(0, 2);
//        NSString *weekString = [source substringWithRange:week];
//        NSLog(@"aaaaaaa周提取出为%@",weekString);
        CalDataModel *model=[[CalDataModel alloc]initWithmingCheng:arrayData[i*4] jiaoShi:arrayData[i*4+3] shiJian:arrayData[i*4+1] laoShi:arrayData[i*4+2] xingQi:0 kaiShiZhou:0 jieShuZhou:0 specialMark:0];
        [cach addObject:model];
    }
        self.allClasses=[[NSArray alloc]initWithArray:cach];
        self.weekList = [self.allClasses mutableCopy];
        for (int n = 0; n<[self.weekList count]; n++) {
            CalDataModel * newdata = [self.weekList objectAtIndex:n];
            if ([newdata.shiJian rangeOfString:@"周一"].location!=NSNotFound){
                newdata.xingQi = 1;
            }else if ([newdata.shiJian rangeOfString:@"周二"].location!=NSNotFound){
                newdata.xingQi = 2;
            }else if ([newdata.shiJian rangeOfString:@"周三"].location!=NSNotFound){
                newdata.xingQi = 3;
            }else if ([newdata.shiJian rangeOfString:@"周四"].location!=NSNotFound){
                newdata.xingQi = 4;
            }else if ([newdata.shiJian rangeOfString:@"周五"].location!=NSNotFound){
                newdata.xingQi = 5;
            }else if ([newdata.shiJian rangeOfString:@"周六"].location!=NSNotFound){
                newdata.xingQi = 6;
            }else if ([newdata.shiJian rangeOfString:@"周日"].location!=NSNotFound){
                newdata.xingQi = 7;
            }
            NSRange judge;
            judge.location = 0;
            judge.length = 1;
            if ([[newdata.shiJian substringWithRange:judge]isEqualToString:@"周" ]){
                
            
            //取开始周
            NSRange testRange = [newdata.shiJian rangeOfString:@"{"];
            NSRange test2 = testRange;
            test2.location = test2.location + 3;;
            if ([[newdata.shiJian substringWithRange:test2]isEqualToString:@"-" ]) {
                testRange.location = testRange.location + 2;
                newdata.kaiShiZhou = [[newdata.shiJian substringWithRange:testRange] intValue];
            }
            else{
                testRange.location = testRange.location +2;
                testRange.length = testRange.length +1;
                newdata.kaiShiZhou = [[newdata.shiJian substringWithRange:testRange] intValue];
            }
            //取结束周
            testRange = [newdata.shiJian rangeOfString:@"-"];
            test2 = testRange;
            test2.location = test2.location + 2;;
            if ([[newdata.shiJian substringWithRange:test2]isEqualToString:@"周" ]) {
                testRange.location = testRange.location + 1;
                newdata.jieShuZhou = [[newdata.shiJian substringWithRange:testRange] intValue];
            }
            else{
                testRange.location = testRange.location +1;
                testRange.length = testRange.length +1;
                newdata.jieShuZhou = [[newdata.shiJian substringWithRange:testRange] intValue];
            }
            //是否单双周
            
            if ([newdata.shiJian rangeOfString:@"单周"].location!=NSNotFound) {
                newdata.specialMark = 1;
            }else if ([newdata.shiJian rangeOfString:@"双周"].location!=NSNotFound){
                newdata.specialMark = 2;
            }else{
                newdata.specialMark = 0;
            }
            
            NSLog(@"bbbbbbbbb%@,%@,%@,%d",newdata.shiJian,[NSString stringWithFormat:@"%d",newdata.kaiShiZhou],[NSString stringWithFormat:@"%d",newdata.jieShuZhou],newdata.specialMark);

            if ([newdata.shiJian rangeOfString:@"第1,2节"].location!=NSNotFound){
                newdata.shiJian = @"1";
            }else if ([newdata.shiJian rangeOfString:@"第3,4节"].location!=NSNotFound){
                newdata.shiJian = @"2";
            }else if ([newdata.shiJian rangeOfString:@"第5,6节"].location!=NSNotFound){
                newdata.shiJian = @"3";
            }else if ([newdata.shiJian rangeOfString:@"第7,8节"].location!=NSNotFound){
                newdata.shiJian = @"4";
            }else if ([newdata.shiJian rangeOfString:@"第9,10节"].location!=NSNotFound){
                newdata.shiJian = @"5";
            }else if ([newdata.shiJian rangeOfString:@"第11,12节"].location!=NSNotFound){
                newdata.shiJian = @"6";
            }

            
            [self.weekList replaceObjectAtIndex:n withObject:newdata];
            
        }

        }
        
        NSLog(@"一共有多少节课！？ Answer is %d",self.weekList.count);
        if ([self localDataNeedToChangeToChengJiListAll:self.weekList]) {
/*
            //保存课程信息到userDefault
            NSMutableArray *savingData = [[NSMutableArray alloc]init];
            for (CalDataModel *cla in self.weekList) {
                NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:cla.mingCheng,@"mingCheng",cla.jiaoShi,@"jiaoShi",cla.shiJian,@"shiJian",[NSNumber numberWithInt: cla.xingQi],@"xingQi",[NSNumber numberWithInt: cla.kaiShiZhou],@"kaiShiZhou",[NSNumber numberWithInt: cla.jieShuZhou],@"jieShuZhou",[NSNumber numberWithInt: cla.specialMark],@"specialMark", nil];
                [savingData addObject:dic];
            }
//            NSData *data =[NSKeyedArchiver archivedDataWithRootObject:[self.weekList copy]];
//            NSLog(@"data is %@",data);
            NSUserDefaults *defaults = [[NSUserDefaults  alloc]initWithSuiteName:@"group.ZhangZhang.TodayExtensionSharingDefaults"];
            [defaults setObject:savingData  forKey:@"ClassesArray"];
            [defaults setObject:@"yes" forKey:@"check"];
            [defaults synchronize];
            
*/
        MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
        NSString* dengLuXueHao=myDelegate.XueHao;
        NSPredicate *predicateStudent = [NSPredicate predicateWithFormat:@"xueHao == %@",dengLuXueHao];
        for (Classes *classes in [Classes MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"ofWho.xueHao == %@",dengLuXueHao]]) {
            [classes MR_deleteEntity];
            }
        NSArray *newArray =[[NSArray alloc]initWithArray:[Classes MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"ofWho.xueHao == %@",dengLuXueHao]]];
        NSLog(@"newArray is %@",newArray);
        NSArray *StudentArray =[Student MR_findAllWithPredicate:predicateStudent];
        Student *studentNow = [StudentArray lastObject];
        for (CalDataModel *new in self.weekList) {
            Classes *classMagicModel = [Classes MR_createEntity];
            classMagicModel.mingCheng = new.mingCheng;
            classMagicModel.biaoJi = [NSNumber numberWithInt:new.specialMark];
            classMagicModel.laoShi = new.laoShi;
            classMagicModel.jieShuZhou = [NSNumber numberWithInt:new.jieShuZhou];
            classMagicModel.kaiShiZhou = [NSNumber numberWithInt:new.kaiShiZhou];
            classMagicModel.jiaoShi = new.jiaoShi;
            classMagicModel.shiJian = new.shiJian;
            classMagicModel.xingQi = [NSNumber numberWithInt:new.xingQi];
            classMagicModel.ofWho = studentNow;
        }
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
            if (success) {
                NSLog(@"课程储存成功啦啦啦啦啦啦");
                [self presentClassesInCalDataModel];
            }else{
                NSLog(@"课程储存失败啦啦啦啦啦");
            }
        }];
        }
        
    }
    
}
-(BOOL)localDataNeedToChangeToChengJiListAll:(NSMutableArray *)array{
    MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString* dengLuXueHao = myDelegate.XueHao;
    NSPredicate *classesOfStudent = [NSPredicate predicateWithFormat:@"ofWho.xueHao == %@",dengLuXueHao];
    NSArray *classesArray =[Classes MR_findAllWithPredicate:classesOfStudent];
    NSLog(@"scoreArray.count == %d",classesArray.count);
    if (classesArray.count==0) {
        return YES;
    }else{
        if (array.count==0) {
            return NO;
        }else{
            for (CalDataModel *classModel in array) {
                NSPredicate *everyclass= [NSPredicate predicateWithFormat:@"ofWho.xueHao == %@ AND mingCheng == %@ AND laoShi == %@ AND shiJian ==%@",dengLuXueHao,classModel.mingCheng,classModel.laoShi,classModel.shiJian];
                if ([Classes MR_findAllWithPredicate:everyclass].count==0) {
                    NSLog(@"find sth new");
                    return YES;
                }
                

            }
            return NO;
        
        }
    
    }
}

-(void)presentClassesInCalDataModel{//将数据库中的class转为datamodel格式的array，并赋值给self.weeklist
    MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString* dengLuXueHao = myDelegate.XueHao;
    NSPredicate *classesOfStudent = [NSPredicate predicateWithFormat:@"ofWho.xueHao == %@",dengLuXueHao];
    NSArray *classArray =[Classes MR_findAllWithPredicate:classesOfStudent];
    NSMutableArray *dataModelArray = [[NSMutableArray alloc]init];
    for (Classes *classInClasses in classArray) {
        CalDataModel *new = [[CalDataModel alloc]initWithmingCheng:classInClasses.mingCheng jiaoShi:classInClasses.jiaoShi shiJian:classInClasses.shiJian laoShi:classInClasses.laoShi xingQi:[classInClasses.xingQi intValue] kaiShiZhou:[classInClasses.kaiShiZhou intValue] jieShuZhou:[classInClasses.jieShuZhou intValue] specialMark:[classInClasses.biaoJi intValue]];
        [dataModelArray addObject:new];
    }
    self.loadingList = dataModelArray;
   
    //保存课程信息到userDefault
    NSMutableArray *savingData = [[NSMutableArray alloc]init];
    for (CalDataModel *cla in self.loadingList) {
        NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:cla.mingCheng,@"mingCheng",cla.jiaoShi,@"jiaoShi",cla.shiJian,@"shiJian",[NSNumber numberWithInt: cla.xingQi],@"xingQi",[NSNumber numberWithInt: cla.kaiShiZhou],@"kaiShiZhou",[NSNumber numberWithInt: cla.jieShuZhou],@"jieShuZhou",[NSNumber numberWithInt: cla.specialMark],@"specialMark", nil];
        [savingData addObject:dic];
    }
    //            NSData *data =[NSKeyedArchiver archivedDataWithRootObject:[self.weekList copy]];
    //            NSLog(@"data is %@",data);
    NSUserDefaults *defaults = [[NSUserDefaults  alloc]initWithSuiteName:@"group.ZhangZhang.TodayExtensionSharingDefaults"];
    [defaults setObject:savingData  forKey:@"ClassesArray"];
    [defaults setObject:@"yes" forKey:@"check"];
    [defaults synchronize];
   // NSLog(@"classArray got %d loadingList got %d week is %d",classArray.count,self.loadingList.count,self.week);
    //self.loadingList = dataModelArray;

}




-(void)clearClass{
    [self.mon removeAllObjects];
    [self.tue removeAllObjects];
    [self.wed removeAllObjects];
    [self.thu removeAllObjects];
    [self.fri removeAllObjects];
    [self.sat removeAllObjects];
    [self.sun removeAllObjects];
}

-(void)setWeek:(int)week{
    
    _week = week;
    [self clearClass];
    [self spreadLoadingListToDayArray];
    //self.loadingList = [self.weekList copy];
    
}
-(AFHTTPRequestOperationManager*)AFHROM{
    if (!_AFHROM) {
        
        _AFHROM=[AFHTTPRequestOperationManager manager];
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
        _AFHROM.responseSerializer.stringEncoding=enc;
        _AFHROM.requestSerializer.stringEncoding = enc;
        _AFHROM.responseSerializer=[AFHTTPResponseSerializer serializer];
        _AFHROM.requestSerializer = [AFHTTPRequestSerializer serializer];
        //        return _AFHROM;
    }
    return _AFHROM;
}



@end
